import { useEffect } from "react";
import { Space, Popconfirm, Table, Tooltip, message, Radio, Badge } from "antd";
import { Button } from "@douyinfe/semi-ui";
import { IconRefresh, IconDelete, IconGlobeStroke, IconEyeOpened } from "@douyinfe/semi-icons";
import { useModel } from "umi";
import { useReactive } from "ahooks";
import { format } from "timeago.js";

import useHelperToolsApplication from "../../helper/useHelperToolsApplication";

import useAllVersions from "../../hooks/application/tools/useAllVersions";
import useDeleteVersion from "../../hooks/application/tools/useDeleteVersion";
import useVersionOnline from "../../hooks/application/tools/useVersionOnline";

const { Column } = Table;

const ApplicationDetailVersions = ({ application, applicationTypes }) => {
    const { runEnv, BNTApplicationOperationCenterUrls } = useModel("global");
    const { openEditApplicationTypeVerionDesc } = useHelperToolsApplication();
    const { submitLoading, deleteApplicationVersion } = useDeleteVersion();
    const { loading, loadAllVersions, versions } = useAllVersions();

    const { handleVersionOnline } = useVersionOnline();

    const state = useReactive({
        selectedType: "全部",
        page: 1,
        pageSize: 5,
        submitLoading: false,
    });

    const loadVersions = () => {
        let appUuid = application.appUuid;
        let apvType = state.selectedType === "全部" ? null : state.selectedType;
        loadAllVersions(appUuid, apvType);
    };

    useEffect(() => {
        if (application?.appUuid) {
            loadVersions();
        }
    }, [application, state.selectedType]);

    const editApplicationTypeVerionDesc = (item) => {
        openEditApplicationTypeVerionDesc(item, loadVersions);
    };

    const submitVersionOnline = (operatorCenter, clientVersion) => {
        if (!clientVersion.apvDesc) {
            message.warning("没有版本更新说明，请添写");
            return editApplicationTypeVerionDesc(clientVersion);
        }
        state.submitLoading = true;
        const clientType = applicationTypes.find((item) => item.appUuid === application.appUuid && item.appType === clientVersion.apvType);
        handleVersionOnline(operatorCenter, application, clientType, clientVersion, loadVersions);
        state.submitLoading = false;
    };

    const deleteVersion = async (record) => {
        const values = {
            appUuid: record.appUuid,
            apvPubtime: record.apvPubtime,
        };
        deleteApplicationVersion(values, (res) => {
            if (res) {
                message.success("成功删除应用客户端版本");
                loadAllVersions();
            }
        });
    };

    const onlineRunEnv = {
        development: [
            { title: "开发环境", runEnv: "dev", url: BNTApplicationOperationCenterUrls.dev },
            { title: "测试环境", runEnv: "testing", url: BNTApplicationOperationCenterUrls.testing },
        ],
        dev: [
            { title: "开发环境", runEnv: "dev", url: BNTApplicationOperationCenterUrls.dev },
            { title: "测试环境", runEnv: "testing", url: BNTApplicationOperationCenterUrls.testing },
        ],
        testing: [
            { title: "测试环境", runEnv: "testing", url: BNTApplicationOperationCenterUrls.testing },
            { title: "生产环境", runEnv: "production", url: BNTApplicationOperationCenterUrls.production },
        ],
        production: [],
    };

    const TableHeader = () => {
        let radios = "";
        if (applicationTypes.length > 1) {
            radios = (
                <Radio.Group value={state.selectedType} onChange={(e) => (state.selectedType = e.target.value)}>
                    <Radio.Button value="全部">全部</Radio.Button>
                    {applicationTypes.map((item, index) => (
                        <Radio.Button key={index} value={item.appType}>
                            {item.appType}
                        </Radio.Button>
                    ))}
                </Radio.Group>
            );
        }
        return (
            <div style={{ display: "flex", justifyContent: "space-between" }}>
                <div style={{ lineHeight: "32px" }}>应用终端版本信息</div>
                <div>{radios}</div>
                <div>
                    <Button icon={<IconRefresh />} onClick={loadVersions}></Button>
                </div>
            </div>
        );
    };

    const pagination = {
        hideOnSinglePage: true,
        pageSize: state.pageSize,
        total: versions.length,
        page: state.page,
        onChange: (page) => (state.page = page),
        itemRender: (_, type, originalElement) => {
            if (type === "prev") return <a style={{ marginRight: 10 }}>上一页</a>;
            if (type === "next") return <a style={{ marginLeft: 10 }}>下一页</a>;
            return originalElement;
        },
    };

    const renderTime = (_) => _ && <Tooltip title={formatUTCTime(_, "YYYY年MM月DD日 HH:ss:mm")}>{format(formatUTCTime(_), "zh_CN")}</Tooltip>;

    const renderDesc = (_, r) =>
        _ ? (
            <Tooltip title={_}>
                <a onClick={() => editApplicationTypeVerionDesc(r)}>
                    <IconEyeOpened />
                </a>
            </Tooltip>
        ) : (
            <a onClick={() => editApplicationTypeVerionDesc(r)}>补充说明</a>
        );

    const renderStatus = (_, r, i) =>
        _ ? (
            <Space>
                <Tooltip title={_["dev"]?.uuid ? `开发环境 ${_["dev"]?.name} ${formatUTCTime(_["dev"]?.time)}` : ""}>
                    <Badge color={_["dev"]?.uuid ? "green" : "red"} />
                </Tooltip>
                <Tooltip title={_["testing"]?.uuid ? `测试环境 ${_["testing"]?.name} ${formatUTCTime(_["testing"]?.time)}` : ""}>
                    <Badge color={_["testing"]?.uuid ? "green" : "red"} />
                </Tooltip>
                <Tooltip title={_["production"]?.uuid ? `生产环境 ${_["production"]?.name} ${formatUTCTime(_["production"]?.time)}` : ""}>
                    <Badge color={_["production"]?.uuid ? "green" : "red"} />
                </Tooltip>
            </Space>
        ) : (
            ""
        );

    const renderOperate = (_, r, i) => {
        return (
            <Space size={0}>
                {!r.apvOnlined && (
                    <Popconfirm placement="topRight" title="确认要删除该应用客户端版本吗?" okButtonProps={{ loading: submitLoading }} onConfirm={() => deleteVersion(r)}>
                        <Button theme="borderless" icon={<IconDelete style={{ color: "#E91E63" }} />}></Button>
                    </Popconfirm>
                )}

                {onlineRunEnv[runEnv].map((item, index) => (
                    <Popconfirm
                        key={index}
                        placement="topRight"
                        title={`确认要上线该应用客户端版本【${item.title}】吗?`}
                        okButtonProps={{ loading: state.submitLoading }}
                        onConfirm={() => submitVersionOnline(item, r)}
                    >
                        <Button key={index} theme="borderless" icon={<IconGlobeStroke />} title={`上线到${item.title}`}></Button>
                    </Popconfirm>
                ))}
            </Space>
        );
    };

    return (
        <Table loading={loading} title={TableHeader} dataSource={versions} rowKey="apvPubtime" bordered size="small" pagination={pagination}>
            <Column title="序号" align="center" width={60} render={(_, r, i) => i + 1 + (state.page - 1) * state.pageSize} />
            <Column title="类型" dataIndex="apvType" align="center" />
            <Column title="版本日期" dataIndex="apvVeda" align="center" />
            <Column title="版本序号" dataIndex="apvVeno" align="center" />
            <Column title="发版人" dataIndex="apvPublisher" align="center" render={(_) => _.name} />
            <Column title="发版时间" dataIndex="apvPubtime" align="center" render={renderTime} />
            <Column title="版本号" dataIndex="apvVersion" align="center" />
            <Column title="代码大小" dataIndex="apvCodesize" align="center" render={(_) => (_ ? helper.byteConvert(parseInt(_)) : "")} />
            <Column title="上线状态" dataIndex="apvOnlined" align="center" render={(_) => (_ ? "已上线" : "-")} />
            <Column title="上线时间" dataIndex="apvOlti" align="center" render={renderTime} />
            <Column title="更新说明" dataIndex="apvDesc" align="center" render={renderDesc} />
            <Column title="上线状态" dataIndex="onlineRecord" align="center" render={renderStatus} />
            <Column title="操作" align="center" width={120} render={renderOperate} />
        </Table>
    );
};

export default ApplicationDetailVersions;
